package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * 切入表达式
     */
//    @Pointcut("execution(*.com.sky.mapper.*.*(..)")
//    public void pt(){}
    @Before("@annotation(autoFill)")
    public void autoFill(JoinPoint jp, AutoFill autoFill) throws Exception {
        //获取原始方法上面@AutoFill注解value属性的值
        OperationType type = autoFill.value();
        //获取原始方法的参数
        Object[] args = jp.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];
        //通过反射为对应的属性赋值
        Class entityClass = entity.getClass();
        Method createTimeMethod = entityClass.getMethod("setCreateTime", LocalDateTime.class);
        Method updateTimeMethod = entityClass.getMethod("setUpdateTime", LocalDateTime.class);
        Method createUserMethod = entityClass.getMethod("setCreateUser", Long.class);
        Method updateUserMethod = entityClass.getMethod("setUpdateUser", Long.class);
        if (type == OperationType.INSERT) {
            createTimeMethod.invoke(entity, LocalDateTime.now());
            updateTimeMethod.invoke(entity, LocalDateTime.now());
            createUserMethod.invoke(entity, BaseContext.getCurrentId());
            updateUserMethod.invoke(entity, BaseContext.getCurrentId());
        } else if (type == OperationType.UPDATE) {
            updateTimeMethod.invoke(entity, LocalDateTime.now());
            updateUserMethod.invoke(entity, BaseContext.getCurrentId());
        }
    }

}
